package com.yunchuang.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 加密工具类
 *
 * @author ItJiange
 * @date 2023/10/21
 */
public class MD5Utils {
    public static String encrypt(String text) {
        try {
            // 创建MD5消息摘要对象
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 将输入文本转换为字节数组
            byte[] textBytes = text.getBytes("UTF-8");

            // 更新消息摘要对象以计算MD5散列
            byte[] digest = md.digest(textBytes);

            // 将字节数组转换为十六进制字符串
            StringBuilder result = new StringBuilder();
            for (byte b : digest) {
                result.append(String.format("%02x", b));
            }

            return result.toString();
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }
}
